import os
import sys

# 保证脚本可在项目根目录直接运行
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__) + '/../'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keepback.settings')

import django
django.setup()

from Login.models import User  # 修正为实际用户模型
from elasticsearch import Elasticsearch

es = Elasticsearch(['http://localhost:9200'])

# 可选：自动创建 users 索引（如已存在可跳过）
def create_users_index():
    if not es.indices.exists(index="users"):
        es.indices.create(
            index="users",
            body={
                "mappings": {
                    "properties": {
                        "id":      { "type": "integer" },
                        "username":{ "type": "text" },
                        "avatar":  { "type": "keyword" },
                        "level":   { "type": "integer" },
                        "points":  { "type": "integer" }
                    }
                }
            }
        )
        print("已创建 users 索引")
    else:
        print("users 索引已存在")

def sync_users():
    users = User.objects.all()
    for user in users:
        doc = {
            "id": user.id,
            "phone": user.phone,
            "created_at": user.created_at.strftime('%Y-%m-%dT%H:%M:%S') if user.created_at else None
        }
        es.index(index="users", id=user.id, document=doc)
    print(f"已同步 {users.count()} 个用户到 ES")

if __name__ == "__main__":
    create_users_index()
    sync_users()
